import { validateUser } from '../../utils/db';
import { generateToken } from '../../utils/jwt';
import type { LoginRequest, ApiResponse
  , LoginResponseData } from '../../../types';
import type { D1Database } from '@cloudflare/workers-types';
import _ from 'lodash';

/**
 * 处理登录请求
 * 这是Nuxt 3.x中推荐的API路由处理方式
 */
export default defineEventHandler(async (event): Promise<ApiResponse<LoginResponseData>> => {
  try {
    const { username, password } = await readBody<LoginRequest>(event);

    if (!username || !password) {
      setResponseStatus(event, 400);
      return {
        success: false,
        message: '用户名和密码不能为空'
      };
    }

    const db = event.context.cloudflare.env.DB as D1Database;
    if (!db) {
      console.error('D1 database binding not found in event context.');
      setResponseStatus(event, 500);
      return {
        success: false,
        message: '服务器配置错误，数据库不可用'
      };
    }

    const user = await validateUser(db, username, password);
    if (!user) {
      setResponseStatus(event, 401); // Unauthorized
      return {
        success: false,
        message: '用户名或密码错误'
      };
    }

    const token = await generateToken({
      id: user.id,
      username: user.username,
      role: user.role
    });

    const safeUser = _.omit(user, ['password', 'role']);
    return {
      success: true,
      message: '登录成功',
      data: {
        user: safeUser,
        token
      }
    };
  } catch (error) {
    console.error('登录处理错误:', error);
    setResponseStatus(event, 500);
    return {
      success: false,
      message: '登录失败，请稍后重试'
    };
  }
});